package com.project.web.admin.controller.common;

import com.project.common.web.utils.config.prop.PropAttributes;
import com.project.common.web.utils.config.prop.PropConfig;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import org.yun.common.utils.plupload.Plupload;
import org.yun.common.utils.plupload.PluploadUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 文件上传-plupload
 */
@Component
public class PluploadController extends AbstractController {

    private static final long serialVersionUID = -1135728345007743005L;

    public Map<String, Object> upload(Plupload plupload, HttpServletRequest request) {

        plupload.setRequest(request);

        //文件存储路径
        //File dir = new File(plupload.getRequest().getSession().getServletContext().getRealPath("/") + PluploadUtil.FILE_DIR);
        File dir = new File(PropConfig.getProperty(PropAttributes.NFS__SERVICE_IMAGE_TEMP_PATH) + "/" + PluploadUtil.FILE_DIR);
        try {
            //上传文件
            PluploadUtil.upload(plupload, dir);
            //判断文件是否上传成功（被分成块的文件是否全部上传完成）
            if (PluploadUtil.isUploadFinish(plupload)) {
                return PluploadUtil.getSuccessResult("url", PropConfig.getProperty(PropAttributes.NFS__SERVICE_IMAGE_TEMP_PATH) + "/" + PluploadUtil.FILE_DIR + plupload.getName());
            }
            return PluploadUtil.getSuccessResult();
        } catch (IllegalStateException e) {
            log.error("文件上传失败：" + ExceptionUtils.getFullStackTrace(e));
            return PluploadUtil.getFailResult();
        } catch (IOException e) {
            log.error("文件上传失败：" + ExceptionUtils.getFullStackTrace(e));
            return PluploadUtil.getFailResult();
        }
    }
}
